package sg.edu.nus.comp.cs4218.impl.fileutils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;

import sg.edu.nus.comp.cs4218.fileutils.ICatTool;
import sg.edu.nus.comp.cs4218.impl.ATool;
import sg.edu.nus.comp.cs4218.impl.Shell;

public class CatTool extends ATool implements ICatTool {

	/**
	 * Constructor
	 * 
	 * @param arguments
	 *            - Arguments the tool is going to be executed with.
	 */
	public CatTool(String[] arguments) {
		super(arguments);
		setStatusCode(0);
	}

	/**
	 * Retrieves contents of specified file
	 * 
	 * @param toRead
	 *            - The file to read from
	 * @return The contents of the file
	 */
	@Override
	public String getStringForFile(File toRead) {
		String content = null;
		// Error Handling
		if (toRead.exists() == false
				|| toRead.isFile() == false) {
			setStatusCode(1);
			return "Error: Cannot find file";
		} else {
			List<String> contentsList;
			try {
				contentsList = Files.readAllLines(toRead.toPath(),
						Charset.forName("UTF8"));
				for (String line : contentsList) {
					if (content == null) {
						content = line;
					} else {
						content = content + "\n" + line.trim();;
					}
				}
			} catch (IOException e) {
				setStatusCode(1);
				content = "Error reading file";
			}
		}
		return content;
	}

	/**
	 * Displays the contents of files listed in order to the screen
	 * 
	 * @param stdin
	 *            - Input on stdin. NOT THE ARGUMENTS! Can be null.
	 * @return Output on stdout
	 */
	@Override
	public String execute(File workingDir, String stdin) {

		String message = null;

		if (super.args == null) {
			setStatusCode(1);
			message = "Invalid cat command";
		}
		
		if (getStatusCode() == 0) {
			if (super.args.length >= 1) {
				for (String file : args) {
					if (file.equals("-") == false && getStatusCode() == 0) {
						File stringFromFile = Shell.getFile(workingDir, file);
						if (message == null) {
							message = getStringForFile(stringFromFile).trim();
						} else {
							message = message + "\n"
									+ getStringForFile(stringFromFile).trim();
						}
					}
					else if (file.equals("-") == true && getStatusCode() == 0) {
						if (stdin != null) {
							if (message == null) {
								message = stdin.trim();
							} else {
								message = message + "\n"
										+ stdin.trim();
							}
						}
						else {
							setStatusCode(1);
							message = "Invalid cat command";
						}
					}
				}
			} else {
				setStatusCode(1);
				message = "Invalid cat command";
			}
		}
		return message;
	}
}
